<template>
  <IDropdown items-class="max-w-xs sm:max-w-sm" v-bind="$attrs" :full="false">
    <template #toggle="{ disabled, noCaret, toggle }">
      <slot :label="toggleLabel" :toggle="toggle">
        <button
          type="button"
          :disabled="disabled"
          :class="toggleClass"
          class="flex w-full items-center rounded-md px-1 text-sm text-neutral-800 hover:text-neutral-500 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2 focus:ring-offset-neutral-300 disabled:pointer-events-none disabled:opacity-60 dark:text-neutral-200 dark:hover:text-neutral-300"
          @click="toggle"
        >
          <slot name="label" :label="toggleLabel">
            {{ toggleLabel }}
          </slot>

          <Icon v-if="!noCaret" icon="ChevronDown" class="ml-1 h-4 w-4" />
        </button>
      </slot>
    </template>

    <div class="overflow-y-auto py-1" :style="{ maxHeight: maxHeight }">
      <slot name="header"></slot>

      <IDropdownSelectItem
        v-for="item in items"
        :key="isObject(item) ? item[valueKey] : item"
        :item="item"
        :condensed="condensed"
        :label-key="labelKey"
        @click="handleClickEvent"
      />

      <slot name="footer"></slot>
    </div>
  </IDropdown>
</template>

<script setup>
import { computed } from 'vue'
import isEqual from 'lodash/isEqual'
import isObject from 'lodash/isObject'

import IDropdownSelectItem from './IDropdownSelectItem.vue'

defineOptions({
  inheritAttrs: false,
})

const props = defineProps({
  modelValue: { required: true },
  label: String,
  condensed: String,
  toggleClass: [Array, Object, String],
  items: { type: Array, default: () => [] },
  maxHeight: { type: String, default: '500px' },
  // If values are object
  labelKey: { type: String, default: 'label' },
  valueKey: { type: String, default: 'value' },
})

const emit = defineEmits(['change', 'update:modelValue'])

const toggleLabel = computed(() => {
  if (props.label) {
    return props.label
  }

  if (isObject(props.modelValue)) {
    return props.modelValue[props.labelKey]
  } else if (
    typeof props.modelValue === 'string' ||
    typeof props.modelValue === 'number' ||
    props.modelValue === null
  ) {
    if (isObject(props.items[0])) {
      let item = props.items.find(
        item => item[props.valueKey] == props.modelValue
      )

      return item ? item[props.labelKey] : ''
    }

    return props.items.find(item => item == props.modelValue) || ''
  }

  return props.modelValue
})

function handleClickEvent(active) {
  emit('update:modelValue', active)

  if (!isEqual(active, props.modelValue)) {
    emit('change', active)
  }
}
</script>
